"""
性能优化API端点
基于测试结果提供性能优化和调试功能
"""
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
import asyncio

from services.monitoring.performance_optimization_coordinator import performance_optimization_coordinator
from services.infrastructure.adaptive_performance_controller import adaptive_performance_controller
from services.infrastructure.multi_level_cache import multi_level_cache
from services.ai_infrastructure.gpu_resource_manager import gpu_resource_manager
from services.monitoring.database_performance_optimizer import database_optimizer
from services.monitoring.real_time_logging_service import logging_service
from services.monitoring.real_time_performance_monitor import performance_monitor

router = APIRouter()


@router.get("/status", summary="获取性能优化状态")
async def get_optimization_status():
    """获取性能优化系统状态"""
    try:
        # 获取各组件状态
        coordinator_report = await performance_optimization_coordinator.get_optimization_report()
        system_status = await performance_monitor.get_system_status()
        cache_stats = await multi_level_cache.get_cache_stats()
        gpu_info = await gpu_resource_manager.get_enhanced_cluster_info()
        db_report = await database_optimizer.get_performance_report()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "overall_health_score": coordinator_report.get('summary', {}).get('system_health_score', 0),
            "system_performance": system_status,
            "optimization_summary": coordinator_report.get('summary', {}),
            "cache_performance": cache_stats.get('overall', {}),
            "gpu_status": gpu_info.get('basic_info', {}),
            "database_performance": db_report.get('summary', {}),
            "recent_optimizations": coordinator_report.get('recent_optimizations', [])[:5]
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取优化状态失败: {str(e)}")


@router.post("/execute", summary="执行性能优化")
async def execute_optimization(background_tasks: BackgroundTasks):
    """执行综合性能优化"""
    try:
        # 在后台执行优化
        background_tasks.add_task(_execute_optimization_background)
        
        return {
            "message": "性能优化已启动",
            "status": "started",
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"启动性能优化失败: {str(e)}")


async def _execute_optimization_background():
    """后台执行性能优化"""
    try:
        result = await performance_optimization_coordinator.execute_comprehensive_optimization()
        await logging_service.log_info("performance_api", 
                                      f"API触发的性能优化完成: {result.performance_improvement:.1f}%改善")
    except Exception as e:
        await logging_service.log_error("performance_api", f"API触发的性能优化失败: {str(e)}")


@router.get("/report", summary="获取性能优化报告")
async def get_optimization_report(hours: int = 24):
    """获取详细的性能优化报告"""
    try:
        # 获取综合报告
        coordinator_report = await performance_optimization_coordinator.get_optimization_report()
        
        # 获取性能监控报告
        performance_report = await performance_monitor.generate_performance_report({
            "type": "detailed",
            "duration_hours": hours
        })
        
        # 获取日志摘要
        log_summary = await logging_service.generate_performance_summary(hours)
        
        # 获取缓存性能报告
        cache_stats = await multi_level_cache.get_cache_stats()
        
        # 获取GPU性能报告
        gpu_report = await gpu_resource_manager.get_gpu_performance_report()
        
        # 获取数据库性能报告
        db_report = await database_optimizer.get_performance_report()
        
        return {
            "report_period": {
                "hours": hours,
                "start_time": (datetime.now() - timedelta(hours=hours)).isoformat(),
                "end_time": datetime.now().isoformat()
            },
            "optimization_coordinator": coordinator_report,
            "system_performance": performance_report,
            "log_analysis": log_summary,
            "cache_performance": cache_stats,
            "gpu_performance": gpu_report,
            "database_performance": db_report,
            "generated_at": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成性能报告失败: {str(e)}")


@router.get("/recommendations", summary="获取性能优化建议")
async def get_optimization_recommendations():
    """获取性能优化建议"""
    try:
        # 获取各组件的优化建议
        recommendations = {
            "adaptive_controller": await adaptive_performance_controller.get_performance_recommendations(),
            "gpu_manager": await gpu_resource_manager.optimize_gpu_allocation(),
            "system_health": []
        }
        
        # 获取系统健康状态
        system_status = await performance_monitor.get_system_status()
        
        # 基于系统状态生成建议
        if system_status.get("cpu_usage", 0) > 85:
            recommendations["system_health"].append({
                "type": "cpu_optimization",
                "priority": "high",
                "description": "CPU使用率过高，建议减少并发处理任务",
                "actions": ["降低处理帧率", "减少并发摄像头数量", "优化AI算法效率"]
            })
        
        if system_status.get("memory_usage", 0) > 80:
            recommendations["system_health"].append({
                "type": "memory_optimization",
                "priority": "high",
                "description": "内存使用率过高，建议清理缓存和优化内存使用",
                "actions": ["清理缓存", "减少批处理大小", "优化数据结构"]
            })
        
        if system_status.get("gpu_usage", 0) > 90:
            recommendations["system_health"].append({
                "type": "gpu_optimization",
                "priority": "critical",
                "description": "GPU使用率过高，建议立即优化GPU资源分配",
                "actions": ["重新分配GPU任务", "降低AI处理精度", "增加GPU资源"]
            })
        
        return {
            "timestamp": datetime.now().isoformat(),
            "system_status": system_status,
            "recommendations": recommendations,
            "total_recommendations": sum(len(recs) if isinstance(recs, list) else 1 
                                       for recs in recommendations.values())
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取优化建议失败: {str(e)}")


@router.post("/cache/optimize", summary="优化缓存系统")
async def optimize_cache():
    """优化缓存系统"""
    try:
        result = await multi_level_cache.optimize_cache()
        
        return {
            "message": "缓存优化完成",
            "optimization_result": result,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"缓存优化失败: {str(e)}")


@router.post("/gpu/rebalance", summary="重新平衡GPU资源")
async def rebalance_gpu_resources():
    """重新平衡GPU资源分配"""
    try:
        success = await gpu_resource_manager.rebalance_gpu_pools()
        
        if success:
            return {
                "message": "GPU资源重新平衡成功",
                "status": "success",
                "timestamp": datetime.now().isoformat()
            }
        else:
            return {
                "message": "GPU资源重新平衡失败",
                "status": "failed",
                "timestamp": datetime.now().isoformat()
            }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"GPU资源重新平衡失败: {str(e)}")


@router.post("/database/optimize", summary="优化数据库性能")
async def optimize_database():
    """优化数据库性能"""
    try:
        result = await database_optimizer.optimize_database_indexes()
        
        return {
            "message": "数据库优化完成",
            "optimization_result": {
                "type": result.optimization_type,
                "description": result.description,
                "performance_improvement": result.performance_improvement,
                "actions_taken": result.actions_taken
            },
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"数据库优化失败: {str(e)}")


@router.get("/metrics/real-time", summary="获取实时性能指标")
async def get_real_time_metrics():
    """获取实时性能指标"""
    try:
        # 获取系统状态
        system_status = await performance_monitor.get_system_status()
        
        # 获取资源使用情况
        resource_usage = await performance_monitor.get_resource_usage()
        
        # 获取缓存统计
        cache_stats = await multi_level_cache.get_cache_stats()
        
        # 获取GPU集群信息
        gpu_cluster = await gpu_resource_manager.get_enhanced_cluster_info()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "system_status": system_status,
            "resource_usage": resource_usage,
            "cache_metrics": {
                "hit_rate": cache_stats.get('overall', {}).get('hit_rate', 0),
                "total_requests": cache_stats.get('overall', {}).get('total_requests', 0),
                "memory_usage": cache_stats.get('memory_cache', {}).get('memory_usage_mb', 0)
            },
            "gpu_metrics": {
                "total_gpus": gpu_cluster.get('basic_info', {}).get('total_gpus', 0),
                "available_gpus": gpu_cluster.get('basic_info', {}).get('available_gpus', 0),
                "average_utilization": gpu_cluster.get('basic_info', {}).get('average_utilization', 0)
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取实时指标失败: {str(e)}")


@router.get("/logs/performance", summary="获取性能相关日志")
async def get_performance_logs(limit: int = 100, level: Optional[str] = None):
    """获取性能相关日志"""
    try:
        # 获取性能相关的日志
        performance_logs = logging_service.get_component_logs("performance_monitor", limit)
        optimization_logs = logging_service.get_component_logs("optimization_coordinator", limit)
        cache_logs = logging_service.get_component_logs("cache_monitor", limit)
        gpu_logs = logging_service.get_component_logs("gpu_manager", limit)
        
        # 合并并按时间排序
        all_logs = performance_logs + optimization_logs + cache_logs + gpu_logs
        all_logs.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
        
        # 应用级别过滤
        if level:
            all_logs = [log for log in all_logs if log.get('level') == level.upper()]
        
        return {
            "total_logs": len(all_logs),
            "logs": all_logs[:limit],
            "log_levels": list(set(log.get('level') for log in all_logs)),
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取性能日志失败: {str(e)}")


@router.post("/config/update", summary="更新性能优化配置")
async def update_optimization_config(config: Dict[str, Any]):
    """更新性能优化配置"""
    try:
        # 验证配置参数
        valid_keys = [
            "auto_optimization_enabled",
            "optimization_interval_seconds",
            "critical_threshold",
            "warning_threshold",
            "min_improvement_threshold"
        ]
        
        invalid_keys = [key for key in config.keys() if key not in valid_keys]
        if invalid_keys:
            raise HTTPException(status_code=400, detail=f"无效的配置键: {invalid_keys}")
        
        # 更新配置
        coordinator = performance_optimization_coordinator
        for key, value in config.items():
            if hasattr(coordinator.optimization_config, key):
                coordinator.optimization_config[key] = value
        
        await logging_service.log_info("performance_api", 
                                     f"性能优化配置已更新: {list(config.keys())}")
        
        return {
            "message": "配置更新成功",
            "updated_config": config,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新配置失败: {str(e)}")


@router.get("/debug/system-state", summary="获取系统调试信息")
async def get_system_debug_info():
    """获取系统调试信息"""
    try:
        # 收集详细的系统调试信息
        debug_info = {
            "timestamp": datetime.now().isoformat(),
            "system_health": {},
            "component_status": {},
            "performance_trends": {},
            "resource_allocation": {},
            "error_analysis": {}
        }
        
        # 系统健康信息
        system_status = await performance_monitor.get_system_status()
        debug_info["system_health"] = system_status
        
        # 组件状态
        coordinator_report = await performance_optimization_coordinator.get_optimization_report()
        debug_info["component_status"] = {
            "optimization_coordinator": {
                "health_score": coordinator_report.get('summary', {}).get('system_health_score', 0),
                "total_optimizations": coordinator_report.get('summary', {}).get('total_optimizations', 0),
                "success_rate": coordinator_report.get('summary', {}).get('success_rate', 0)
            }
        }
        
        # 性能趋势
        debug_info["performance_trends"] = coordinator_report.get('performance_trends', {})
        
        # 资源分配
        gpu_info = await gpu_resource_manager.get_enhanced_cluster_info()
        debug_info["resource_allocation"] = {
            "gpu_pools": gpu_info.get('gpu_pools', {}),
            "task_distribution": gpu_info.get('task_distribution', {}),
            "memory_pools": gpu_info.get('memory_pools', {})
        }
        
        # 错误分析
        error_logs = logging_service.get_error_logs(50)
        error_types = {}
        for log in error_logs:
            error_type = log.get('metadata', {}).get('error_type', 'unknown')
            error_types[error_type] = error_types.get(error_type, 0) + 1
        
        debug_info["error_analysis"] = {
            "recent_errors": len(error_logs),
            "error_types": error_types,
            "top_errors": error_logs[:10]
        }
        
        return debug_info
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取调试信息失败: {str(e)}")


@router.post("/debug/force-optimization", summary="强制执行性能优化")
async def force_optimization(optimization_type: str = "comprehensive"):
    """强制执行性能优化（调试用）"""
    try:
        if optimization_type == "comprehensive":
            result = await performance_optimization_coordinator.execute_comprehensive_optimization()
        elif optimization_type == "cache":
            result = await multi_level_cache.optimize_cache()
        elif optimization_type == "gpu":
            suggestions = await gpu_resource_manager.optimize_gpu_allocation()
            result = {"suggestions": len(suggestions), "actions": [s.description for s in suggestions[:3]]}
        elif optimization_type == "database":
            result = await database_optimizer.optimize_database_indexes()
            result = result.__dict__
        else:
            raise HTTPException(status_code=400, detail=f"不支持的优化类型: {optimization_type}")
        
        return {
            "message": f"{optimization_type}优化执行完成",
            "optimization_result": result,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"强制优化失败: {str(e)}")